package com.vito.framework.system.user.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vito.framework.base.controller.BaseController;
import com.vito.framework.base.exception.CommonException;
import com.vito.framework.rest.bean.AppSession;
import com.vito.framework.system.org.model.OrgBean;
import com.vito.framework.system.org.service.OrgManageService;
import com.vito.framework.system.role.model.RoleBean;
import com.vito.framework.system.user.model.UserBean;
import com.vito.framework.system.user.service.UserService;
import com.vito.support.ApiResponse;
import com.vito.support.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/***************************************************************
 * Name:        MenuAction.java    
 * Module:      用户管理
 * Description: [用户管理-用户管理增删改查功能]
 * ------------------------------------------------------------
 * 修改历史
 * 序号  日期  修改人   修改原因
 * 1
 * 2
 ***************************************************************/
@RestController
@RequestMapping("${adminPath}/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private OrgManageService orgService;

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [用户管理-查询用户列表]
	 *
	 * @return String
	 */
	@PostMapping(value = "list", consumes = "application/json;charset=UTF-8")
	public ApiResponse list(HttpServletRequest request, @RequestBody JSONObject params) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}
	
		paramMap.put("param_siId", paramMap.get("cur_orgId"));
		paramMap.put("userId", paramMap.get("cur_userId"));
		paramMap.put("param_keyword", params.getString("param_keyword"));
		UserBean userBean = userService.getUserById(paramMap);
		try {
			//系统管理员查看全部
			if("0".equals(userBean.getUserType())) {
				paramMap.remove("param_siId");
			} else {
				//非系统管理员只能查看系统管理员之下的账号
				paramMap.put("param_userType", 1);
			}
			List<UserBean> resultList = userService.getUserList(paramMap);
			return ApiResponse.ok(resultList);
		} catch(CommonException e) {
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [用户管理-点击添加按钮，进入添加页面]
	 *
	 * @return String
	 */
	@PostMapping(value = "listByLevel", consumes = "application/json;charset=UTF-8")
	public ApiResponse listByLevel(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		Map<String, Object> resMap = new HashMap<>();

		String siId = (String) paramMap.get("cur_orgId");
		String userId=(String) paramMap.get("cur_userId");
		paramMap.put("param_siId", siId);
		paramMap.put("userId", userId);
		UserBean userBean = userService.getUserById(paramMap);
		List<OrgBean> orgList = orgService.getOrgManageList(new HashMap<>());
		String orgLevel = userBean.getOrgLevel();
		if(!StrUtil.isEmpty(orgLevel)) {
			//非一级机构只能查看自己所在的机构
			if(Integer.parseInt(orgLevel) > 1) {
				Iterator<OrgBean> it = orgList.iterator();
				while(it.hasNext()) {
					OrgBean org = it.next();
					if(!StrUtil.isEmpty(org.getOrgId()) && !siId.equals(org.getOrgId())) {
						it.remove();
					}
				}
			}
		}
		paramMap.put("param_userId", userId);
		resMap.put("orgList", orgList);
		resMap.put("userBean", new UserBean());
		resMap.put("loginUserType", userBean.getUserType());
		return ApiResponse.ok(resMap);
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [用户管理-点击修改按钮，进入修改页面]
	 *
	 * @return String
	 */
	@PostMapping(value = "get", consumes = "application/json;charset=UTF-8")
	public ApiResponse get(HttpServletRequest request, @RequestBody JSONObject params) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		Map<String, Object> resMap = new HashMap<>();

		String userId = params.getString("userId");
		paramMap.put("userId", userId);
		try {
			UserBean userBean = userService.getUserById(paramMap);
			List<RoleBean> roleList = null;
			if(!StrUtil.isEmpty(userBean.getOrgId())) {
				roleList = userService.getRoleByOrgId(userBean.getOrgId());
			}
			List<OrgBean> orgList = orgService.getOrgManageList(new HashMap<>());
			//非一级机构只能查看自己所在的机构

			UserBean loginUser = userService.getLoginUserById(paramMap);
			String orgLevel = loginUser.getOrgLevel();
			String siId = StrUtil.isEmpty(userBean.getOrgId()) ? loginUser.getOrgId() : userBean.getOrgId();
			if(!StrUtil.isEmpty(orgLevel)) {
				if(Integer.parseInt(orgLevel) > 1) {
					Iterator<OrgBean> it = orgList.iterator();
					while(it.hasNext()) {
						OrgBean org = it.next();
						if(!StrUtil.isEmpty(org.getOrgId()) && !siId.equals(org.getOrgId())) {
							it.remove();
						}
					}
				}
			}
	
			resMap.put("method", "edit");
			resMap.put("roleList", roleList);
			resMap.put("orgList", orgList);
			resMap.put("userBean", userBean);
			resMap.put("loginUserType", loginUser.getUserType());
			return ApiResponse.ok(resMap);
		} catch(CommonException e) {
			return ApiResponse.of(e);
		}
	}

	@PostMapping(value = "getRoleListByOrg", consumes = "application/json;charset=UTF-8")
	public ApiResponse getRoleListByOrg(HttpServletRequest request, @RequestBody JSONObject params) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		String orgId = params.getString("orgId");
		if(StrUtil.isEmpty(orgId)) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}
		List<RoleBean> roleList = null;
		try {
			roleList = userService.getRoleByOrgId(orgId);
			return ApiResponse.ok(roleList);
		} catch(CommonException e) {
			e.printStackTrace();
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:zhaowentao
	 * Create At:2010-04-22
	 * Description: [用户管理-添加用户，保存用户信息]
	 *
	 * @return String
	 */
	@PostMapping(value = "add", consumes = "application/json;charset=UTF-8")
	public ApiResponse add(HttpServletRequest request, @RequestBody JSONObject params, UserBean userBean) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		try {
			userBean= JSONObject.toJavaObject(params, UserBean.class);
			userService.addUser(userBean);
			return ApiResponse.ok(ResultEnum.OK);
		} catch(CommonException e) {
			ApiResponse.of(e);
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [用户管理-修改用户，保存用户信息]
	 *
	 * @return String
	 */
	@PostMapping(value = "update", consumes = "application/json;charset=UTF-8")
	public ApiResponse update(HttpServletRequest request, @RequestBody JSONObject params, UserBean userBean) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}
		userBean= JSONObject.toJavaObject(params, UserBean.class);
		if (null == userBean) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		try {
			userService.editUser(userBean);
			return ApiResponse.ok(ResultEnum.OK);
		} catch(CommonException e) {
			ApiResponse.of(e);
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [用户管理-暂停用户信息]
	 *
	 * @return String
	 */
	@PostMapping(value = "pause", consumes = "application/json;charset=UTF-8")
	public ApiResponse pause(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		String siId =  (String) paramMap.get("cur_orgId");
		String userId=params.getString("userId");
		String[] ids=userId.split(",");
		paramMap.put("ids", ids);
		paramMap.put("orgId", siId);
		try {
			userService.pauseUser(paramMap);
			return ApiResponse.ok(ResultEnum.OK);
		} catch(CommonException e) {
			ApiResponse.of(e);
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [用户管理-启动用户信息]
	 *
	 * @return String
	 */
	@PostMapping(value = "reStart", consumes = "application/json;charset=UTF-8")
	public ApiResponse reStart(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}
		String siId = (String) paramMap.get("cur_orgId");
//		List<String> idList = JSONArray.parseArray(params.getJSONArray("ids").toJSONString(), String.class);
//		String ids[] = idList.toArray(new String[idList.size()]);
		String userId=params.getString("userId");
		String[] ids=userId.split(",");
		paramMap.put("ids", ids);
		paramMap.put("orgId", siId);
		try {
			userService.reStartUser(paramMap);
			return ApiResponse.ok(ResultEnum.OK);
		} catch(CommonException e) {
			ApiResponse.of(e);
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [用户管理-删除用户信息]
	 *
	 * @return String
	 */
	@PostMapping(value = "delete", consumes = "application/json;charset=UTF-8")
	public ApiResponse delete(HttpServletRequest request, @RequestBody JSONObject params) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		String siId = (String) paramMap.get("cur_orgId");
		String userId = (String) paramMap.get("cur_userId");
		List<String> idList = JSONArray.parseArray(params.getJSONArray("ids").toJSONString(), String.class);
		String ids[] = idList.toArray(new String[idList.size()]);
		paramMap.put("ids", ids);
		paramMap.put("siId", siId);
		paramMap.put("userId", userId);
		try {
			userService.deleteUser(paramMap);
			return ApiResponse.ok(ResultEnum.OK);
		} catch(CommonException e) {
			ApiResponse.of(e);
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-05
	 * Description: [系统管理-初始页面，查询用户信息列表,验证用户名不可重复]
	 *
	 * @return String
	 */
	@PostMapping(value = "checkReId", consumes = "application/json;charset=UTF-8")
	public ApiResponse checkReId(HttpServletRequest request, @RequestBody JSONObject params) throws Exception {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		String userId = "";
		paramMap.put("param_userName", params.getString("param_userName"));
		try {
			UserBean userBean = null;
			userBean = userService.getUserByName(paramMap);
			if(userBean != null) {
				userId = userBean.getUserId();
			}
			return ApiResponse.ok(userId);
		} catch(CommonException e) {
			ApiResponse.of(e);
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:futiantian
	 * Create At:2017-07-06
	 * Description: [系统管理-初始页面，查询用户信息列表,验证用户名不可重复]
	 *
	 * @return String
	 * @throws Exception
	 */
	@PostMapping(value = "checkUserId", consumes = "application/json;charset=UTF-8")
	public ApiResponse checkUserId(HttpServletRequest request, @RequestBody JSONObject params) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		paramMap.put("param_adminAccount", params.getString("param_adminAccount"));

		try {
			String count = userService.queryTemplateList(paramMap);
			return ApiResponse.ok(count);
		} catch(CommonException e) {
			e.printStackTrace();
			return ApiResponse.of(e);
		}
	}

	/**
	 * Author:zhaowentao
	 * Create At:2011-9-1
	 * Description: [修改密码-保存密码]
	 *
	 * @return String
	 * @throws Exception
	 */
	@PostMapping(value = "changePassword", consumes = "application/json;charset=UTF-8")
	public ApiResponse changePassword(HttpServletRequest request, @RequestBody JSONObject params) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		String oldPassword = params.getString("oldPassword");
		String newPassword = params.getString("newPassword");
		String resTxt = "failure";
		if(oldPassword == null || oldPassword.trim().length() == 0 || newPassword == null || newPassword.trim().length() == 0) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		} else {
			paramMap.put("oldPassword", oldPassword);
			paramMap.put("newPassword", newPassword);
			try {
				Integer result = userService.updatePassword(paramMap);
				if(result != null && result == 1) {
					resTxt = "success";
				} else if(result == 0) {
					resTxt = "incorrectPWD";
				}
				return ApiResponse.ok(resTxt);
			} catch(CommonException e) {
				return ApiResponse.of(e);
			}
		}
	}

	/**
	 * Author:zhaowentao
	 * Create At:2011-9-1
	 * Description: [个人资料-用户修改个人资料]
	 *
	 * @return String
	 * @throws Exception
	 */
	@PostMapping(value = "savePresonInfo", consumes = "application/json;charset=UTF-8")
	public ApiResponse savePresonInfo(HttpServletRequest request, @RequestBody JSONObject params, UserBean userBean) {
		Map<String, Object> resMap = new HashMap<>();
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}
		AppSession session = super.getUserSession(request);	

		String siId = session.getMerchantId();
		userBean.setOrgId(siId);
		try {
			userService.savePresonInfo(userBean);
			if(userBean.getEmail() != null) {
				resMap.put("USER_EMAIL", userBean.getEmail());
			}
			if(userBean.getMobile() != null) {
				resMap.put("USER_MOBILE", userBean.getMobile());
			}
			return ApiResponse.ok(resMap);
		} catch(CommonException e) {
			ApiResponse.of(e);
			return ApiResponse.of(e);
		}
	}
	//机构查询管理员
	@PostMapping(value = "getGlyList", consumes = "application/json;charset=UTF-8")
	public ApiResponse getGlyList(HttpServletRequest request, @RequestBody JSONObject params) {
		Map<String, Object> paramMap = super.getParamMap(request,params);
		if(null == paramMap) {
			return ApiResponse.of(ResultEnum.PARAMS_INVALID);
		}

		paramMap.put("param_keyword", params.getString("param_keyword"));

		try {
			String orgId=params.getString("orgId");
			paramMap.put("param_siId", orgId);
    		List<UserBean> resultList=userService.getUserList(paramMap);
			return ApiResponse.ok(resultList);
		} catch(CommonException e) {
			e.printStackTrace();
			return ApiResponse.of(e);
		}
	}
	//机构新增管理员
		@PostMapping(value = "orgAdmin", consumes = "application/json;charset=UTF-8")
		public ApiResponse orgAdmin(HttpServletRequest request, @RequestBody JSONObject params) {
			Map<String, Object> paramMap = super.getParamMap(request,params);
			if(null == paramMap) {
				return ApiResponse.of(ResultEnum.PARAMS_INVALID);
			}

			try {
				OrgBean orgBean=new OrgBean();
				orgBean.setOrgId(params.getString("orgId"));
				orgBean.setAdminAccount(params.getString("account"));
				orgBean.setAdminPassword(params.getString("password"));
				orgService.adminAdd(orgBean);
				return ApiResponse.ok(ResultEnum.OK);
			} catch(CommonException e) {
				e.printStackTrace();
				return ApiResponse.of(e);
			}
		}
		@PostMapping(value = "getAdminInfo", consumes = "application/json;charset=UTF-8")
		public ApiResponse getAdminInfo(HttpServletRequest request, @RequestBody JSONObject params, UserBean userBean) {
			Map<String, Object> paramMap = super.getParamMap(request,params);
			if(null == paramMap) {
				return ApiResponse.of(ResultEnum.PARAMS_INVALID);
			}

			try {
				userBean=userService.getUserByuserid(params.getString("userId"));
				return ApiResponse.ok(userBean);
			} catch(CommonException e) {
				ApiResponse.of(e);
				return ApiResponse.of(e);
			}
		}
		@PostMapping(value = "editAdmin", consumes = "application/json;charset=UTF-8")
		public ApiResponse editAdmin(HttpServletRequest request, @RequestBody JSONObject params,UserBean userBean) {
			Map<String, Object> paramMap = super.getParamMap(request,params);
			if(null == paramMap) {
				return ApiResponse.of(ResultEnum.PARAMS_INVALID);
			}
			try {
				userBean= JSONObject.toJavaObject(params, UserBean.class);
				userService.editGly(userBean);
				return ApiResponse.ok(ResultEnum.OK);
			} catch(CommonException e) {
				e.printStackTrace();
				return ApiResponse.of(e);
			}
		}
		@PostMapping(value = "delAdmin", consumes = "application/json;charset=UTF-8")
		public ApiResponse delAdmin(HttpServletRequest request, @RequestBody JSONObject params,UserBean userBean) {
			Map<String, Object> paramMap = super.getParamMap(request,params);
			if(null == paramMap) {
				return ApiResponse.of(ResultEnum.PARAMS_INVALID);
			}
			try {
				String[] ids=params.getString("userId").split(",");
				paramMap.put("ids", ids);
				userService.deleteUser(paramMap);
				return ApiResponse.ok(ResultEnum.OK);
			} catch(CommonException e) {
				e.printStackTrace();
				return ApiResponse.of(e);
			}
		}
}